package org.hilo.boot.app.component;

import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.logging.LogLevel;
import org.springframework.boot.logging.LoggingSystem;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.core.ConfigConsts;
import com.ctrip.framework.apollo.model.ConfigChangeEvent;
import com.ctrip.framework.apollo.spring.annotation.ApolloConfig;
import com.ctrip.framework.apollo.spring.annotation.ApolloConfigChangeListener;

/**
 * 动态调整线上日志输出，方便排查问题
 * @author zollty
 * @since 2018-5-3
 */
@Service
@ConditionalOnClass(com.ctrip.framework.apollo.Config.class)
public class DynamicLoggersConfig {
    private final static String LOGGER_TAG = "logging.level.";

    private Logger logger = LoggerFactory.getLogger(getClass());

    @ApolloConfig
    private Config config;

    private final LoggingSystem loggingSystem;

    public DynamicLoggersConfig(LoggingSystem loggingSystem) {
        Assert.notNull(loggingSystem, "LoggingSystem must not be null");
        this.loggingSystem = loggingSystem;
    }

    @ApolloConfigChangeListener({ConfigConsts.NAMESPACE_APPLICATION})
    private void configChangeListener(ConfigChangeEvent changeEvent) {
        Set<String> keyNames = config.getPropertyNames();
        for (String key : keyNames) {
            if (key.indexOf(LOGGER_TAG) != -1) {
                String strLevel = config.getProperty(key, "info");
                LogLevel level = LogLevel.valueOf(strLevel.toUpperCase());
                loggingSystem.setLogLevel(key.replace(LOGGER_TAG, ""), level);
                logger.info("Adjust Logger level {}:{}", key, strLevel);
            }
        }
    }
}
